#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2023, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

# Reads all files in **CURRENT DIRECTORY and SUBDIRECTORIES** and looks
# for the section labels which contain the setup code of the bundled
# Ruby gems. Replaces the content with the one configured below.

# Section begin and end labels
RG_SETUP_BEGIN = '%%RUBYGEMS_SETUP_BEGIN%%'
RG_SETUP_END   = '%%RUBYGEMS_SETUP_END%%'

# Bundled Ruby gems loader code.
# IMPORTANT: Update here and commit into Git as well!
# rubocop:disable Layout/HeredocIndentation
RG_SETUP = <<-EOT
if File.directory?(GEMS_LOCATION)
    real_gems_path = File.realpath(GEMS_LOCATION)
    if !defined?(Gem) || Gem.path != [real_gems_path]
        $LOAD_PATH.reject! {|l| l =~ /vendor_ruby/ }

        # Suppress warnings from Rubygems
        # https://github.com/OpenNebula/one/issues/5379
        begin
            verb = $VERBOSE
            $VERBOSE = nil
            require 'rubygems'
            Gem.use_paths(real_gems_path)
        ensure
            $VERBOSE = verb
        end
    end
end
EOT
# rubocop:enable Layout/HeredocIndentation

#####

SCRIPT_FILE = File.expand_path(__FILE__)

updated = []

# iterate over all files
Dir.glob('**/*') do |name|
    next if File.directory?(name) || File.expand_path(name) == SCRIPT_FILE

    old = File.read(name, :encoding => 'iso-8859-1')

    # detect right files by checking for the begin section label
    if old.include?(RG_SETUP_BEGIN)
        unless old.include?(RG_SETUP_END)
            STDERR.puts "ERROR: File #{name} doesn't contain RG end label"
            exit 1
        end

        # replace all text inside labels by RG_SETUP code
        new = old.gsub(
            /(#{RG_SETUP_BEGIN}[^\n]*).*\n([^\n]*#{RG_SETUP_END})/m,
            "\\1\n#{RG_SETUP.chomp}\n\\2"
        )

        if new != old
            updated << name

            File.open(name, 'w') do |f|
                f.write(new)
            end
        end
    end
end

# report
if updated.empty?
    STDERR.puts 'WARNING: No files updated'
else
    STDERR.puts "Updated #{updated.length} files:"
    puts updated.join("\n")
end
